#include				<iostream>
#include				"SoundManager.h"
#include				"EncodedSoundPacket.h"
#include				"Order.h"

SoundManager::SoundManager()
{
	Pa_Initialize();
	Listener *tmp = new Listener();
	connect(tmp, SIGNAL(_readBufferFull()), this, SLOT(readBufferFull()));
	_listener = tmp;
	_speaker = new Speaker();
	_encoder = new Encoder();
	_decoder = new Decoder();
	_encoder->init();
	_decoder->init();
	_listener->init();
	_speaker->init();
	//_listener->start();
	//_speaker->start();
}


SoundManager::~SoundManager()
{
	Pa_Terminate();
	delete _speaker;
	delete _listener;
	delete _decoder;
	delete _encoder;
}

void					SoundManager::readBufferFull()
{
	SoundPacket			*packet = new SoundPacket;

	_listener->read(packet);
	emit _readBufferFull(packet);
}

void					SoundManager::takeOrder(IOrder *order)
{
	SoundPacket			*packet = new SoundPacket;

	_decoder->decode(order, packet);
	//play(packet);
}

void					SoundManager::play(ISoundPacket *pack, unsigned int stamp)
{
	_speaker->write(pack, stamp);
}

ISoundPacket			*SoundManager::decode(IEncodedSoundPacket *enc)
{
	SoundPacket			*packet = new SoundPacket;
	_decoder->decode(enc, packet);
	return packet;
}

IEncodedSoundPacket		*SoundManager::encode(ISoundPacket *packet)
{
	EncodedSoundPacket			*enc = new EncodedSoundPacket;
	_encoder->encode(packet, enc);
	return enc;
}

void					SoundManager::decode(IEncodedSoundPacket *enc, ISoundPacket *packet)
{
	_decoder->decode(enc, packet);
}

void					SoundManager::encode(ISoundPacket *packet, IEncodedSoundPacket *enc)
{
	_encoder->encode(packet, enc);
}

void					SoundManager::setInput(bool state)
{
	if (!state)
		_listener->stop();
	else
		_listener->start();
}

void					SoundManager::setOutput(bool state)
{
	if (!state)
		_speaker->stop();
	else
		_speaker->start();
}